const fs = require('fs');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const config = require('../config/config');

class FileService {
  constructor(chatService) {
    this.chatService = chatService;
    this.fileUploads = new Map();
    this.ensureUploadDir();
  }

  async ensureUploadDir() {
    try {
      await fs.promises.mkdir(config.UPLOAD_DIR, { recursive: true });
    } catch (error) {
      console.error('创建上传目录失败:', error);
    }
  }

  async handleImageMessage(clientId, data) {
    const client = this.chatService.clientService.getClient(clientId);
    if (!client?.nickname) return;

    try {
      const base64Data = data.url.split(',')[1];
      const buffer = Buffer.from(base64Data, 'base64');
      const filename = `${uuidv4()}_${data.filename}`;
      const filepath = path.join(config.UPLOAD_DIR, filename);

      await fs.promises.writeFile(filepath, buffer);

      const msg = {
        type: 'image',
        clientId: clientId,
        nickname: client.nickname,
        url: `/uploads/${filename}`,
        filename: data.filename,
        timestamp: Date.now()
      };

      await this.chatService.messageService.saveMessage(msg);
      this.chatService.broadcast(msg);
    } catch (error) {
      console.error('图片保存失败:', error);
    }
  }

  initializeFileUpload(clientId, data) {
    try {
      const uploadId = uuidv4();
      const filePath = path.join(config.UPLOAD_DIR, `${uploadId}_${data.filename}`);
      const writeStream = fs.createWriteStream(filePath);

      writeStream.on('error', (error) => {
        console.error('文件写入错误:', error);
        this.fileUploads.delete(clientId);
      });

      this.fileUploads.set(clientId, {
        writeStream,
        filename: data.filename,
        fileType: data.fileType,
        size: data.size,
        uploadId: uploadId,
        filePath: filePath,
        thumbnail: data.thumbnail
      });
    } catch (error) {
      console.error('初始化文件上传失败:', error);
    }
  }

  handleFileChunk(clientId, chunk) {
    try {
      const upload = this.fileUploads.get(clientId);
      if (!upload) return;
      upload.writeStream.write(Buffer.from(chunk));
    } catch (error) {
      console.error('处理文件块失败:', error);
    }
  }

  async finalizeFileUpload(clientId) {
    const upload = this.fileUploads.get(clientId);
    if (!upload) return;

    const client = this.chatService.clientService.getClient(clientId);
    if (!client?.nickname) return;

    const isVideo = upload.fileType?.startsWith('video/');
    const msg = {
      type: isVideo ? 'video' : 'file',
      clientId: clientId,
      nickname: client.nickname,
      url: `/uploads/${upload.uploadId}_${upload.filename}`,
      filename: upload.filename,
      fileType: upload.fileType,
      size: upload.size,
      thumbnail: upload.thumbnail,
      timestamp: Date.now()
    };

    try {
      await new Promise((resolve) => {
        upload.writeStream.end(() => resolve());
      });

      await this.chatService.messageService.saveMessage(msg);
      this.chatService.broadcast(msg);

      client.ws.send(JSON.stringify({ type: 'fileSaved' }));
    } catch (error) {
      console.error('文件上传完成处理失败:', error);
      client.ws.send(JSON.stringify({
        type: 'error',
        message: '文件保存失败'
      }));
    } finally {
      this.cleanupFileUpload(clientId);
    }
  }

  cleanupFileUpload(clientId) {
    const upload = this.fileUploads.get(clientId);
    if (upload) {
      upload.writeStream.end();
      this.fileUploads.delete(clientId);
    }
  }
}

module.exports = FileService;